function calculate(str) {
    const reg = /(\d+)\s*([+\-*/])\s*(\d+)/;
    const match = str.match(reg);
    if (!match) {
        throw new Error('Invalid input');
    }
    const [_, num1, operator, num2] = match;
    const n1 = parseInt(num1, 10);
    const n2 = parseInt(num2, 10);
    switch (operator) {
        case '+':
            return n1 + n2;
        case '-':
            return n1 - n2;
        case '*':
            return n1 * n2;
        case '/':
            if (n2 === 0) {
                throw new Error('Divide by zero');
            }
            return n1 / n2;
        default:
            throw new Error('Invalid operator');
    }
}

// 测试
console.log(calculate('1 + 2')); // 3
console.log(calculate('3 - 2')); // 1
console.log(calculate('2 * 3')); // 6
console.log(calculate('4 / 2')); // 2